<template>
    <div v-if="rechargeSwitch" v-loading="firstLoading">
        <el-card class="!border-none" shadow="never">
            <div class="instruments">
                <div class="panel-item">
                    <div class="text-[23px] text-primary">
                        {{ userQuota.points }}
                    </div>
                    <div class="mt-[4px]">剩余{{ appStore.getAmountUnit }}</div>
                </div>
                <div class="panel-item">
                    <div class="text-[23px] text-primary">
                        <span class="text-3xl">
                            {{ userQuota?.train?.usage_num }}
                        </span>/{{ userQuota?.train?.total_num }}
                    </div>
                    <div class="mt-[4px]">训练组数</div>
                </div>
                <div class="panel-item">
                    <div class="text-[23px] text-primary">
                        <span class="text-3xl">
                            {{ userQuota?.robot?.usage_num }}
                        </span>/{{ userQuota?.robot?.total_num }}
                    </div>
                    <div class="mt-[4px]">智能体数</div>
                </div>
                <div class="panel-item">
                    <div class="text-[23px] text-primary">
                        <span class="text-3xl">
                            {{ userQuota?.know?.usage_num }}
                        </span>/{{ userQuota?.know?.total_num }}
                    </div>
                    <div class="mt-[4px]">知识库数</div>
                </div>
                <div class="panel-item">
                    <div class="text-[23px] text-primary">
                        <span class="text-3xl">
                            {{ userQuota?.mcp?.usage_num }}
                        </span>/{{ userQuota?.mcp?.total_num }}
                    </div>
                    <div class="mt-[4px]">MCP数</div>
                </div>
            </div>
        </el-card>

        <template v-if="packages.length > 0">
            <el-card class="!border-none" shadow="never">
                <div class="text-xl font-medium mb-[20px]">选择套餐</div>
                <div class="packages">
                    <div
                        v-for="(item, index) in (packages as RechargePackageResponse[])"
                        :key="index"
                        class="item"
                        :class="{ active: index === currentIndex }"
                        @click="currentIndex = index"
                    >
                        <div class="text-xl font-medium mb-[10px] line-clamp-1">{{ item.name }}</div>
                        <span v-if="item.tags" class="tags">
                            {{ item.tags }}
                        </span>
                        <div>
                            <price
                                :content="item.sell_price"
                                main-size="28px"
                                minor-size="16px"
                            />
                        </div>
                        <div class="mb-2">
                            <price
                                :content="item.line_price"
                                prefix="原价:￥"
                                main-size="14px"
                                minor-size="12px"
                                line-through
                                color="#999"
                            />
                        </div>
                        <div class="border-t border-solid border-br-light pt-[10px]">
                            <template v-for="(spec, i) in specifics" :key="i">
                                <div
                                    v-if="extractNumber(item, spec.key)"
                                    class="text-sm flex py-[5px]"
                                >
                                    <span class="text-tx-secondary mr-auto">
                                        {{ spec.label }}：
                                    </span>
                                    <span class="text-tx-regular">
                                        {{ extractNumber(item, spec.key) }}{{ spec.unit }}
                                    </span>
                                </div>
                            </template>

                        </div>
                    </div>
                </div>
            </el-card>

            <el-card class="!border-none" shadow="never">
                <div class="text-xl font-medium mb-[20px]">支付方式</div>
                <PaymentSelect v-model="payWay" from="recharge"/>
            </el-card>

            <el-card class="!border-none" shadow="never">
                <div class="flex justify-between">
                    <div>
                        实付金额:
                        <price
                            :content="currentPackage.sell_price"
                            main-size="24px"
                            minor-size="14px"
                            color="#FF7021"
                        />
                    </div>
                    <el-button
                        type="primary"
                        size="large"
                        style="padding: 0 54px;"
                        :loading="isLock"
                        @click="payNow"
                    >
                        立即充值
                    </el-button>
                </div>
            </el-card>
        </template>

        <div v-else class="flex justify-center">
            <el-empty description="暂无套餐" />
        </div>
    </div>

    <div v-else class="flex justify-center h-full">
        <el-empty
            description="充值已关闭"
            :image-size="200"
        />
    </div>
</template>

<script setup lang="ts">
import { pay, PayWayEnum } from '~/utils/pay'
import useAppStore from '~/stores/app'
import useUserStore from '~/stores/user'
import userApi from '~/api/user/index'
import paymentApi from '@/api/payment'
import rechargeApi from '@/api/recharge'

const appStore = useAppStore()
const userStore = useUserStore()
const rechargeSwitch = computed(() => appStore.getSwitchConfig.recharge)

// 首次加载
const firstLoading = ref<boolean>(true)

// 套餐数据
const payWay = ref<number>(PayWayEnum.WXPAY)
const packages = ref<RechargePackageResponse[]>([])
const userQuota = ref({} as UserQuotaResponse)

// 套餐信息
const specifics = [
    {
        key: 'points_num',
        label: '积分数量',
        unit: '点'
    },
    {
        key: 'train_num',
        label: '训练组数',
        unit: '条'
    },
    {
        key: 'robot_num',
        label: '智能体数',
        unit: '个'
    },
    {
        key: 'know_num',
        label: '知识库数',
        unit: '个'
    },
    {
        key: 'mcp_num',
        label: 'MCP数',
        unit: '个'
    }
]

// 充值套餐
const currentIndex = ref(0)
const currentPackage = computed<RechargePackageResponse>(() => {
    return packages.value[currentIndex.value] || {}
})

// 发起支付
const {lockFn: payNow, isLock} = useLockFn(async () => {
    // 创建订单
    const packageId = parseInt(currentPackage.value?.id || '0')
    const orderInfo = await rechargeApi.place({
        package_id: packageId
    })

    // 预付下单
    const payInfo = await paymentApi.prepay({
        order_id: orderInfo.order_id,
        pay_way: payWay.value,
        attach: 'recharge'
    })

    // 拉起支付
    await pay.run({
        payWay: payWay.value,
        orderId: orderInfo.order_id,
        config: payInfo,
        attach: 'recharge'
    }).then(async () => {
        await userStore.getUser()
        feedback.alertSuccess('支付成功')
    }).catch(() => {})
})

/**
 * 提取数值
 *
 * @param item
 * @param key
 * @author zero
 */
const extractNumber = (item: any, key: string) => {
    return item[key]
}

onMounted(async () => {
    userQuota.value = await userApi.quota()
    packages.value = await rechargeApi.package()
    firstLoading.value = false
})
</script>

<style scoped lang="scss">
.instruments {
    display: flex;
    width: 100%;
    padding: 10px;
    border: 1px dashed var(--el-border-color-light);
    border-radius: 8px;
    .panel-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 33.33%;
        padding: 15px 0;
        margin-right: 10px;
        font-weight: 500;
        background-color: var(--el-bg-color-page);
        border-radius: 8px;
    }
}

.packages {
    display: flex;
    flex-wrap: wrap;
    .item {
        position: relative;
        box-sizing: border-box;
        width: 210px;
        height: 280px;
        padding: 30px 20px;
        margin: 0 15px 15px;
        cursor: pointer;
        border: 1px solid var(--el-border-color-light);
        border-radius: 8px;
        &.active,
        &:hover {
            background-color: var(--el-color-primary-light-9);
            border-color: var(--el-color-primary);
        }
        .tags {
            position: absolute;
            top: -2px;
            left: -2px;
            height: 24px;
            padding: 0 4px;
            font-size: 13px;
            line-height: 24px;
            color: var(--color-white);
            background: linear-gradient(90deg, #fc5531, #fc1944);
            border-radius: 6px 0 8px;
        }

        // .tags {
        //     position: relative;
        //     z-index: 2;
        //     height: 22px;
        //     margin: 25px 0 10px;
        //     font-size: 16px;
        //     font-weight: 700;
        //     line-height: 22px;
        //     color: var(--el-text-color-regular);
        // }
    }
}
</style>
